<template>
  <div class="register">
	<view class="title">
		<view>注册</view>
		<view class="describe">Welcome to ChatAi</view>
	</view>

    <div class="loginbox">
		<view class="forms">
			<el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm">
				
				
				<el-form-item prop="email" >
					<el-input type="email" v-model="ruleForm.email" placeholder="請輸入您的电子郵箱"></el-input>
				</el-form-item>
				<el-form-item prop="sms" class="sms">
				  <el-input v-model="ruleForm.sms" placeholder="請輸入驗證碼">
					<el-button v-show="show" slot="append" ref="popups" @click="NECaptcha(active)" class="yzm">獲取驗證碼</el-button>
					<el-button v-show="!show" slot="append" ref="popups" style="margin: 0; text-align: center">{{ count }}</el-button>
				  </el-input>
				  <!-- <span class="hint" v-if="active === 'email'">Please check the verification code in the inbox or spam</span> -->
				</el-form-item>
				<el-form-item prop="login_password">
				  <el-input placeholder="請輸入密碼" v-model="ruleForm.login_password" show-password></el-input>
				</el-form-item>
				<el-form-item>
				  <el-input placeholder="請輸入邀請碼" v-model="ruleForm.inviter_code" :readonly="mdf === 'f' ? true : false"></el-input>
				</el-form-item>
				<el-form-item style="margin-bottom:8px">
				  <el-button type="primary" class="submit" @click="submitForm('ruleForm')">確認</el-button>
				</el-form-item>
				<el-form-item>
				  <router-link :to="{ path: '/pages/login', query: { invite: ruleForm.inviter_code } }">
					<span class="fr link">登入</span>
				  </router-link>
				</el-form-item>
				<el-form-item>
					<div class="google">
					<div id="signInDiv" class="google-button"></div>
				  </div></el-form-item>
			</el-form>
		</view>
    </div>
    <div id="captcha"></div>
  </div>
</template>

<script>
import generateID from '@/utils/generateID'
import { setToken } from '@/utils/auth'
import md5 from 'js-md5'
import regionData from '../static/json/region.json'

export default {
	name: 'register',
	data() {
		var validatePass = (rule, value, callback) => {
			if (value) {
				let z_reg = /((?=.*[a-z])(?=.*\d)|(?=[a-z])(?=.*[#@!~%^&*])|(?=.*\d)(?=.*[#@!~%^&*]))[a-z\d#@!~%^&*]{6,12}/i
				if (z_reg.test(value)) {
				  callback()
				} else {
				  callback('The password requires 6-12 digits (number / English case / mixed symbol) format')
				}
			}
		}
		return {
			ruleForm: {
				attribution: 66,
				username: '',
				sms: '',
				login_password: null,
				inviter_code: ''
			},
			region: '',
			regionList: regionData,
			rules: {
				attribution: [{ required: true, message: '選擇國家/地區', trigger: 'blur' }],
				username: [
					{
						required: true,
						message: '請輸入手機號',
						trigger: 'blur'
					}
				],
				sms: [
					{
						required: true,
						message: '請輸入驗證碼',
						trigger: 'blur'
					}
				],
				login_password: [
					{
						required: true,
						message: '請輸入密碼',
						trigger: 'blur'
					}
				]
			},
			captchaPoup: null,
			timer: null,
			show: true,
			count: '',
			active: 'email',
			mdf: 't',
			// facebook login
			fbSignInParams: {
				scope: 'email,user_likes',
				return_scopes: true,
				invite: ''
			},
			googleSignInParams: {
				client_id: '807827053401-carip6q42m3jds7mbrcmee35jbgr7s3m.apps.googleusercontent.com'
			}
		}
	},

  methods: {
    // async getIPServer() {
    //   const { code, data } = await this.$api.login.getIP()
    //   if (code == 200) {
    //     this.attribution = data ? this.getCode(data.code) : 66
    //   }
    // },
    // Obtain code from cn
    // getCode(cn) {
    //   regionData.forEach((item) => {
    //     if (item.cn == cn) {
    //       return item.code
    //     }
    //   })
    // },
    // submit
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // let user = JSON.parse(JSON.stringify(this.ruleForm))
          let ruleFormNew = {}
         ruleFormNew = {
           attribution: 66,
           username: this.ruleForm.username,
           sms: this.ruleForm.sms,
           login_password: md5(this.ruleForm.login_password).toUpperCase(),
           inviter_code: this.ruleForm.inviter_code
         }
          // user.login_password = md5(user.login_password).toUpperCase()
          let params = new FormData()
          params.append('reqNo', generateID())
          params.append('data', JSON.stringify(ruleFormNew))
     //      if (this.active === 'email') {
     //        this.$api.register.saveEmail(ruleFormNew).then((res) => {
     //          if (res.code == '200') {
     //            const that = this
     //            this.$message({
     //              message: res.msg,
     //              type: 'success',
     //              onClose: () => {
     //                // that.$router.push({ path: '/pages/login', query: { active: this.active } })
					// that.$router.push({ path: '/pages/login' })
     //              }
     //            })
     //          } else {
     //            this.$message.error(res.msg)
     //          }
     //        })
     //      }
		   // else {
     //        this.$api.register.save(params).then((res) => {
     //          if (res.code == '200') {
     //            const that = this
     //            this.$message({
     //              message: res.msg,
     //              type: 'success',
     //              onClose: () => {
     //                that.$router.push({ path: '/pages/login', query: { active: this.active } })
     //              }
     //            })
     //          } else {
     //            this.$message.error(res.msg)
     //          }
     //        })
     //      }
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    /**
     * Countdown for obtaining verification code
     */
    countDown() {
      const TIME_COUNT = 60
      if (!this.timer) {
        this.count = TIME_COUNT
        this.show = false
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--
          } else {
            this.show = true
            clearInterval(this.timer)
            this.timer = null
          }
        }, 1000)
      }
    },
    /** Obtain mobile phone verification code */
    // getCode(validate) {
    //   let jsonObj = {
    //     username: this.ruleForm.username,
    //     NECaptchaValidate: validate,
    //     attribution: this.ruleForm.attribution
    //   }
    //   let params = new FormData()
    //   params.append('reqNo', generateID())
    //   params.append('data', JSON.stringify(jsonObj))
    //   this.$api.register.getCode(params).then((res) => {
    //     if (res.code == '200') {
    //       this.$message({
    //         message: res.msg,
    //         type: 'success'
    //       })
    //       this.countDown()
    //     } else {
    //       this.$message.error(res.msg)
    //     }
    //   })
    // },
    /**
     * Obtain the email verification code
     */
    getEmailCode(validate) {
      // this.$api.register.getEmailCode()
      let jsonObj = {
        email: this.ruleForm.email,
        NECaptchaValidate: validate,
		sendType: 1
      }
      let params = new FormData()
      params.append('reqNo', generateID())
      params.append('data', JSON.stringify(jsonObj))
      this.$api.register.getEmailCode(jsonObj).then((res) => {
        this.countDown()
      })
    },
    NECaptcha(val) {
      let that = this
      initNECaptcha(
        {
          captchaId: '0726bf5935ec47db8452cbb795df5f03',
          element: '#captcha',
          mode: 'popup',
          width: '320px',
          lang: 'en',
          onVerify: function (err, data) {
            if (!err) {
              var validata = data.validate
              if (val === 'email') {
                that.getEmailCode(validata)
              }
			  // else if (val === 'mobile') {
     //            that.getCode(validata)
     //          }
            }
          }
        },
        function (instance) {
          that.captchaPoup = instance
          that.captchaPoup.popUp()
        },
        function (err) {}
      )
    },
    tabs(val) {
      this.active = val
      this.$refs['ruleForm'].clearValidate()
    },
    // facebook login
    onSignInSuccess(response) {
      // https://developers.facebook.com/docs/graph-api/reference/user
      FB.api('/me?fields=id,name,gender,first_name,last_name,email,birthday,hometown', (dude) => {
        if (response.status == 'connected') {
          const params = {
            input_token: response.authResponse.accessToken,
            inviter_code: this.ruleForm.inviter_code,
            login_type: 'f'
          }
          this.$api.login.registerFacebook(params).then((res) => {
            if (res.code == '200') {
              let data = JSON.parse(res.data)
              setToken(data.token)
              localStorage.setItem('user', res.data)
              this.$router.push('/pages/home/index')
            }
          })
        }
      })
    },
    onSignInError(error) {},
    // google login
    // google login
    async callbackLogin(response) {
      console.log('response', response)
      const accessToken = response.credential
      const params = {
        input_token: accessToken,
        inviter_code: this.ruleForm.inviter_code,
        login_type: 'g'
      }
      this.$api.login.registerFacebook(params).then((res) => {
        if (res.code == '200') {
          let data = JSON.parse(res.data)
          setToken(data.token)
          localStorage.setItem('user', res.data)
          this.$router.push('/pages/home/index')
        }
      })
    },
    initClient() {
		this.client = google.accounts.id.initialize({
			client_id: '807827053401-carip6q42m3jds7mbrcmee35jbgr7s3m.apps.googleusercontent.com',
			callback: (response) => this.callbackLogin(response)
		})
    }
  },
  mounted() {
    // this.getIPServer()

    // google login
    const googleBtnConfigs = {
      theme: 'outline',
      size: 'large',
      shape: 'pill',
      text: 'login_with',
      width: '50',
      locale: 'en'
    }
	google.accounts.id.prompt()
	google.accounts.id.renderButton(document.getElementById('signInDiv'), googleBtnConfigs)
  },
  created() {
    const query = this.$route.query
    this.ruleForm.inviter_code = this.fbSignInParams.invite = query.invite ? query.invite : ''
    //this.active = query.active ? query.active : 'email'
    this.active = 'email'
    this.mdf = query.m ? query.m : 't'

    !(function (f, b, e, v, n, t, s) {
      if (f.fbq) return
      n = f.fbq = function () {
        n.callMethod ? n.callMethod.apply(n, arguments) : n.queue.push(arguments)
      }
      if (!f._fbq) f._fbq = n
      n.push = n
      n.loaded = !0
      n.version = '2.0'
      n.queue = []
      t = b.createElement(e)
      t.async = !0
      t.src = v
      s = b.getElementsByTagName(e)[0]
      s.parentNode.insertBefore(t, s)
    })(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js')
    fbq('init', '1831726497203282')
    fbq('track', 'PageView')

    !(function (f, b, e, v, n, t, s) {
      if (f.fbq) return
      n = f.fbq = function () {
        n.callMethod ? n.callMethod.apply(n, arguments) : n.queue.push(arguments)
      }
      if (!f._fbq) f._fbq = n
      n.push = n
      n.loaded = !0
      n.version = '2.0'
      n.queue = []
      t = b.createElement(e)
      t.async = !0
      t.src = v
      s = b.getElementsByTagName(e)[0]
      s.parentNode.insertBefore(t, s)
    })(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js')
    fbq('init', '260732735192244')
    fbq('track', 'PageView')

    !(function (f, b, e, v, n, t, s) {
      if (f.fbq) return
      n = f.fbq = function () {
        n.callMethod ? n.callMethod.apply(n, arguments) : n.queue.push(arguments)
      }
      if (!f._fbq) f._fbq = n
      n.push = n
      n.loaded = !0
      n.version = '2.0'
      n.queue = []
      t = b.createElement(e)
      t.async = !0
      t.src = v
      s = b.getElementsByTagName(e)[0]
      s.parentNode.insertBefore(t, s)
    })(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js')
    fbq('init', '1816023618776354')
    fbq('track', 'PageView')

    this.initClient()
  }
}
</script>
<noscript><img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=1831726497203282&ev=PageView&noscript=1"/></noscript>
<noscript><img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=260732735192244&ev=PageView&noscript=1"/></noscript>
<noscript><img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=1816023618776354&ev=PageView&noscript=1"/></noscript>
<style lang="scss">
.register {
	font-family: 'Gilroy';
	position: relative;
	min-height:1400rpx;
	height: 100%;
	background:#000002 url('../static/images/loginBg.png') no-repeat center bottom;
	
	/deep/ .title {
		width: 100%;
		padding-top:26rpx;
		font:400 36rpx/36rpx Arial;
		color: #fff;
		text-align: center;
		.describe {
			padding:40rpx 20rpx 20rpx 20rpx;
			font: 600 60rpx/60rpx Arial;
			text-align: center;
		}
	}
	
	.loginbox {
		position: absolute;
		top:200rpx;
		bottom: 0;
		width: 100%;
		// height: calc(100% - 450rpx);
		
		
		padding: 0 60rpx;
		box-sizing: border-box;
		h4 {
			font: 500 56rpx/150rpx Arial;
			text-align: center;
		}
		.login-tabs {
			display: flex;
			width: 100%;
			height: 96rpx;
			border: 1px solid #ccc;
			border-radius: 48rpx;
			margin-bottom: 6rpx;
			.item {
				flex: 1;
				width: 100%;
				height: 84rpx;
				line-height: 84rpx;
				margin: 6rpx;
				text-align: center;
				font-size: 32rpx;
				font-weight: 500;
				color: #666;
				cursor: pointer;
				&.active {
					color: #8286cf;
					border-radius: 48rpx;
					background-color: #e6e7fc;
				}
			}
		}
		
		.forms {
			margin-top:10rpx;
			
			.link {
				color: rgba(255, 255, 255, 0.5);
				font: 400 24rpx/60rpx Arial;
			}
			.submit {
				margin-top:12rpx;
				width: 100%;
				height: 100rpx !important;
				font-size: 32rpx;
				font-weight:bold;
				color:rgba(255, 255, 255, 1);
				border-radius: 5px;
				background:#2446CA !important;
				border:0;
			}
			/deep/ .username {
				position: relative;
				.el-input__inner {
					padding-left: 100rpx;
				}
				.el-input__suffix {
					position: absolute;
					left: 30rpx;
					right: auto;
					line-height: 96rpx;
					color: #999;
				}
			}
			.sms {
				position: relative;
				
				.hint {
					position: absolute;
					left: 0;
					bottom: -30rpx;
					// display: inline-block;
					font-size: 20rpx;
					color: #f56c6c;
					z-index: 999;
					height: 40rpx;
					line-height: 20rpx;
					
				}
				.el-form-item__error {
					width: 100%;
					z-index: 9999;
					background-color: #fff;
				}
			}
			.el-input-group__append {
			  border-radius: 46rpx;
			  border: 0px  !important;
			  background-color:red  !important;
			  .el-button {
				  height: 96rpx;
				  border-radius:2rpx;
				  border: 0px solid transparent !important;
				  background-color:transparent !important;
			  }
			  .yzm{
			  	display: inline-block;
				height:52rpx;
				line-height: 52rpx;
			  	padding:0;
			  	border-radius: 5px;
			  	border: 0px solid transparent !important;
			  	background-color: rgba(255, 255, 255, 0.1) !important;
			  }
			}
		}
	}
}
.google {
	margin-top: 3rem;
	text-align: center;
	.google-button {
		display: inline-block;
		text-align: center;
	}
	#signInDiv {
		iframe {
			margin: 0 !important;
			left: calc(50% - 105px) !important;
		}
	}
}
</style>
